package com.leinao.job.service.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.leinao.job.dao.PaiJobStatisticsMapper;
import com.leinao.job.service.JobService;

/**
 * @author  wangshoufa 
 * @date 2018年12月5日 下午4:18:08
 *
 */
@Service
public class JobServiceImpl implements JobService {
	
	private  Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	PaiJobStatisticsMapper paiJobStatisticsMapper;
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Value("${remote.loginUrl}")
	private String loginUrl;
	
	@Value("${remote.loadJobUrl}")
	private String loadJobUrl;
	
	@Value("${remote.userName}")
	private String username;
	
	@Value("${remote.password}")
	private String password;

	@Override
	public void statisJobCount() {
		String token = authToken();
		if(StringUtils.isNotBlank(token)) {
			HttpHeaders headers = new HttpHeaders();
	        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
	        headers.setContentType(type);
	        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
	        headers.add("Authorization", "Bearer " + token);
	        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
			String body = "";
			try {
				ResponseEntity<String> responseEntity = restTemplate.exchange(loadJobUrl, HttpMethod.GET, formEntity, String.class);
				logger.info("request getAllJobInfo return: " + responseEntity);
				if(responseEntity.getStatusCodeValue() == 200) {
					logger.info("get jobs success");
					body = responseEntity.getBody();
					JSONArray jsonArray = JSON.parseArray(body);
					Integer runCount = 0;
					Integer waitCount = 0;
					Integer stopCount = 0;
					Integer failCount = 0;
					Integer successCount = 0;
					Integer endCount = 0;
					for(int i = 0; i < jsonArray.size(); i++) {
						JSONObject jsonObject = (JSONObject) jsonArray.get(i);
						String user_id = jsonObject.getString("userId");
						String state = jsonObject.getString("state");
						String executionType = jsonObject.getString("executionType");
						if(state.equals("RUNNING") && !executionType.equals("STOP")) {
							runCount ++;
						}
						if(state.equals("WAITING") && !executionType.equals("STOP")) {
							waitCount ++;
						}
						if(executionType.equals("STOP")) {
							stopCount ++;
						}
						if(state.equals("FAILED")) {
							failCount ++;
						}
						if(state.equals("SUCCEEDED")) {
							successCount ++;
						}
					}
					endCount = successCount;
					stopCount = failCount + stopCount;
				}
			} catch (Exception e) {
				logger.error("get jobs error");
				logger.error(e.getMessage(), e);
			}
		}
	}
	
	
	private String authToken() {
		String token = "";
		try {
			MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
			map.add("username", username);
			map.add("password", password);
			Integer expiration = 1 * 2 * 60 * 60;
			map.add("expiration", expiration.toString());
			logger.info("auth start...");
			String resBody = restTemplate.postForObject(loginUrl, map, String.class);
			logger.info("request auth return: " + resBody);
			JSONObject reponse = JSON.parseObject(resBody);
			token = reponse.getString("token");
			logger.info(token);
		} catch (Exception e) {
			logger.error("token auth error");
			logger.error(e.getMessage(),e);
		}
		return token;
	}
	

}
